import React, { Component } from "react";
import { Upload, Button, Icon, Modal, message, Checkbox, Tooltip, Input } from "antd";
import { inject, observer } from "mobx-react";
import { toJS } from "mobx";
import Zmage from "react-zmage";
import $ from "jquery";
import {
    base64_to_str,
    str_to_base64,
    deselect_checkbox_border_immediately_without_checking,
    add_delete_button_function_to_delete_box,
    delete_button_style,
    highlighting,
    unique,
    img_format_size,
    picture_lazy_load
} from "../../utils/utils";
@inject("standard_face_database_store")
@inject("AdminStore")
@observer
export default class Right_part extends Component {
    constructor(props) {
        super(props);
        this.state = {
            new_face_visible: false, img_base64: undefined, hover_what: undefined,
            visible: false,
            fileList: [],//上传图片的文件列表
            uoload_what: undefined,
            begin_upload: false,
            hover_what: undefined,
            show_check_box: false,
            click_all_clicked_state: false,
            upload_pop_up_title: undefined,
            delete_body_array_state: [],
            delete_body_image_array_state: [],
            number_of_data_uploaded_successfully: 0,
            select_all_or_cancel: "全选",
            select_all_disabled_state: true,
            cancel_which_component: undefined,
            how_many_people_are_there_state: undefined,
            stop_uploading: false,
            whether_the_enlarged_picture_is_visible: false,
            number_of_filtered_pictures: 0,
            is_there_any_picture_that_does_not_conform_to_the_format_state: false,
            upload_file_name: undefined,//要上传的文件名
            upload_file: undefined,//要上传的文件
            need_add_name: false,//上传的文件需要再加上一个名字么
            refresh_get_message: '刷新人体库',
            resfrsh_page: 0,//用于刷新页面,
            checked_arr: [],
            blacklist: [],//上传图片的黑名单
            uploaded_photo: [],//上传过的图片 }
            per_page: 27,
            people_name: '',
            img_base64: '',
            confirmLoading: false,
            refresh_page: 0
        }
    }
    refresh_page = () => {
        this.setState((prevState) => ({
            refresh_page:this.state.refresh_page++
        }))
    }
    static getDerivedStateFromProps(props, state) {
        if (props.standard_face_database_store.faceStoreList.length > 0) {
            state.select_all_disabled_state = false;
        } else {
            state.select_all_disabled_state = true;
            delete_button_style("select_all_button");
        }
    }
    componentDidMount = async () => {

    }
    render() {
        return (
            <React.Fragment>
                <div className="buttons">
                    <Button
                        className="select_all_button chooseAll "
                        disabled={this.state.select_all_disabled_state}//全选按钮
                        onClick={async () => {
                            if (this.state.select_all_or_cancel === "全选") {
                                const store_result = await this.props.standard_face_database_store.ListsAllElementsOfTheFeatureLibrary(this.props.standard_face_database_store.nowChoseWhichFaceStore, this.props.AdminStore.token)
                                this.setState(prevState => ({
                                    show_check_box: true,
                                    click_all_clicked_state: true,
                                    select_all_or_cancel: "取消",
                                    delete_body_array_state: store_result,
                                }));
                                let checked_arr = []
                                for (let [index, item] of this.state.delete_body_array_state.entries()) {
                                    checked_arr.push(item.user)
                                }
                                this.setState((prevState) => ({
                                    checked_arr: checked_arr
                                }))
                                //选中所有
                            } else {
                                this.setState(prevState => ({
                                    show_check_box: false,
                                    click_all_clicked_state: false,
                                    delete_body_array_state: [],
                                    delete_body_image_array_state: [],
                                    select_all_or_cancel: "全选"
                                }));
                            }
                        }}

                    >全选</Button>
                    <Button
                        className="delete_human_button button_hover"
                        disabled={!this.state.click_all_clicked_state}
                        onClick={() => {
                            this.mass_delete_body_pop_up_function();//批量删除人脸函数
                        }}
                    >删除人脸</Button>
                    <Button
     
                        onClick={() => {
                            this.setState((prevState) => ({
                                people_name: '',
                                img_base64: ''
                            }), () => {
                                this.setState((prevState) => ({
                                    new_face_visible: true,
                                }))
                            })
                        }}>新建人脸</Button>
                </div>
                <div className="human_body_management_ul ren_ti_ru_ku_right_ul">
                    {this.props.standard_face_database_store.faceStoreList.length === 0 ? <div className="no_data_class"><div className="no_data_word">暂无数据</div></div> 
                    : this.props.standard_face_database_store.faceStoreList.map((item, index) => {
                        return (
                            <li
                                // key={item}
                                onMouseEnter={() => {
                                    this.setState(prevState => ({
                                        hover_what: item.user
                                    }));
                                }}
                                onMouseLeave={() => {
                                    this.setState(prevState => ({
                                        hover_what: null
                                    }));
                                }}
                            >
                                <div className="ren_ti_jian_suo_right_ul_li_img_wrap">
                                    {
                                        this.props.standard_face_database_store.load_face_img && < a
                                            onClick={() =>
                                                Zmage.browsing({//修改这行代码记得下面还有一行和这个一模一样的
                                                    src: `/face/v1/image/store/${str_to_base64(base64_to_str(this.props.standard_face_database_store.nowChoseWhichFaceStore) + base64_to_str(item.user))}`
                                                })
                                            }
                                        >
                                            <div
                                                onClick={() => {
                                                    let that = this
                                                    $(function () {
                                                        $("#zmageImage").replaceWith(
                                                            `<div class="imageLayer__33OvN" id="zmageImage" style="background:url('/face/v1/image/store/${str_to_base64(base64_to_str(that.props.standard_face_database_store.nowChoseWhichFaceStore) + base64_to_str(item.user))}');visibility: visible"></div>`);
                                                        $('#zmageBackground').append('<div class="delete_icon_class"></div>')
                                                    })
                                                }}
                                                style={{
                                                    backgroundImage: "url(" + require('../../assets/img/人体检索/暂无数据.png') + ")"
                                                }}
                                                data-src={`/face/v1/image/store/${str_to_base64(base64_to_str(this.props.standard_face_database_store.nowChoseWhichFaceStore) + base64_to_str(item.user))}`}
                                                className="ren_ti_jian_suo_right_ul_li_img"
                                            >
                                            </div>
                                        </a>}



                                </div>
                                <Checkbox
                                    className="check_box"
                                    onChange={e => {
                                        this.select_my_check_box_function(item, e);//复选框函数
                                        let checked_arr = []
                                        for (let [index, item] of this.state.delete_body_array_state.entries()) {
                                            checked_arr.push(item.user)
                                        }
                                        console.log(this.state.checked_arr)
                                        this.setState((prevState) => ({
                                            checked_arr: checked_arr
                                        }))
                                        deselect_checkbox_border_immediately_without_checking("check_box");//立即取消复选框的边框
                                    }}
                                    style={{
                                        display: this.state.show_check_box ? "block" : "none",
                                        color: "#fff"
                                    }}
                                    checked={this.state.checked_arr.indexOf(item.user) > -1}
                                ></Checkbox>
                                <div
                                    className="delete_human_body_picture_class"
                                    style={{
                                        display:
                                            this.state.hover_what === item.user &&
                                                !this.state.click_all_clicked_state
                                                ? "block"
                                                : "none"
                                    }}
                                    onClick={() => {
                                        Modal.confirm({//单个删除人脸
                                            title: "请确认是否删除人脸？",
                                            okText: "确认",
                                            okType: "danger",
                                            cancelText: "取消",
                                            width: "300px",
                                            className: "modal_comfirm",
                                            centered: "true",
                                            onOk: async () => {
                                                this.setState(prevState => ({
                                                    show_check_box: false,
                                                    click_all_clicked_state: false,
                                                    select_all_or_cancel: "全选"
                                                }));
                                                await this.props.standard_face_database_store.HumanCharacterLibraryRemovesElements(
                                                    item.user,
                                                    this.props.standard_face_database_store.nowChoseWhichFaceStore,
                                                    this.props.AdminStore.token
                                                );
                                                await this.props.standard_face_database_store.DeleteImageFun(
                                                    str_to_base64(base64_to_str(this.props.standard_face_database_store.nowChoseWhichFaceStore) + base64_to_str(item.user)), this.props.AdminStore.token,
                                                );
                                                await this.list_and_set()
                                                this.lazy_load()
                                            },
                                        });
                                    }}
                                    onMouseEnter={() => {
                                        $(".delete_human_body_picture_class").addClass("deleteImgDeep");
                                    }}
                                    onMouseLeave={() => {
                                        $(".delete_human_body_picture_class").removeClass("deleteImgDeep");
                                    }}
                                ></div>
                                <div className="ren_ti_jian_suo_right_ul_li_people_icon_name_wrap">
                                    <div className="ren_ti_jian_suo_right_ul_li_people_icon"></div>
                                    <div className="ren_ti_jian_suo_right_ul_li_people_name">
                                        <Tooltip title={item.user.indexOf('-') > -1 ? item.user : base64_to_str(item.user)}>
                                            <span>
                                                {
                                                    item.user.indexOf('-') > -1 ? item.user.length > 7 ? item.user.substring(0, 7) + "..." :
                                                        item.user : (base64_to_str(item.user).length > 7
                                                            ? base64_to_str(item.user).substring(0, 7) + "..."
                                                            : base64_to_str(item.user))
                                                }
                                            </span>
                                        </Tooltip>
                                    </div>
                                </div>
                            </li>
                        );
                    })}
                </div>
                <Modal
                    // 新建人脸modal
                    title="新建人脸"
                    className="new_face_store_toast_0"
                    visible={this.state.new_face_visible}
                    okText="确认"
                    cancelText="取消"
                    centered="true"
                    confirmLoading={this.state.confirmLoading}
                    onOk={async () => {

                        const res = await this.handleOk(
                            this.state.img_base64,
                            this.state.people_name,
                            this.props.standard_face_database_store.nowChoseWhichFaceStore,
                            this.props.AdminStore.token
                        );
                        console.log(res)
                        if (res) {
                            this.setState((prevState) => ({
                                new_face_visible: false,
                                confirmLoading: false
                            }), async () => {
                                await this.get_detail_information()
                                this.lazy_load()
                            })
                        }else{
                            this.setState((prevState)=>({
                                confirmLoading: false
                            }))
                        }
                    }}
                    onCancel={this.handleCancel}
                >
                    <div className="new_people_modal_desc_div">
                        人脸名称：
            <Input
                            className="new_face_input"
                            placeholder="最多7个字符"
                            onChange={(e) => {
                                let value = e.target.value
                                this.setState((prevState) => ({
                                    people_name: value
                                }))
                            }}
                            value={this.state.people_name}
                            type="text"
                        />
                    </div>

                    <Upload
                        className="choose_img_upload"
                        showUploadList={false}
                        beforeUpload={this.beforeUpload}
                    >
                        <div className="choose_img_A">
                            {this.state.img_base64 ? (
                                <div className="choose_img_wrap">
                                    <div className="choose_img_wrap_img"
                                        id="uploaded_img_idA"
                                        style={
                                            {
                                                backgroundImage: `url(${this.state.img_base64})`
                                            }
                                        }
                                    >
                                    </div>
                                </div>
                            ) : (
                                    <div className="choose_img_upload_icon_choose_img_word_wrap">
                                        <div className="choose_img_upload_icon "></div>
                                        <div className="choose_img_word">选择图片</div>
                                    </div>
                                )}
                        </div>
                    </Upload>
                </Modal>
            </React.Fragment >
        );
    }
    mass_delete_body_pop_up_function() {//批量删除人脸函数
        Modal.confirm({
            title: "请确认是否删除人脸？",
            content: "",
            okText: "确认",
            content: "",
            okType: "danger",
            cancelText: "取消",
            width: "300px",
            className: "modal_comfirm",
            centered: "true",
            onOk: async () => {
                $(function () {
                    $(".delete_human_button").removeAttr("style");
                });
                for (let [index, item] of this.state.delete_body_array_state.entries()) {//人体特征库删除人体
                    await this.props.standard_face_database_store.HumanCharacterLibraryRemovesElements(//删除人体函数
                        item.user,
                        this.props.standard_face_database_store.nowChoseWhichFaceStore,
                        this.props.AdminStore.token
                    );
                    await this.props.standard_face_database_store.DeleteImageFun(str_to_base64(base64_to_str(this.props.standard_face_database_store.nowChoseWhichFaceStore) + base64_to_str(item.user)));//删除图片函数
                }
                this.setState(prevState => ({
                    show_check_box: false,
                    click_all_clicked_state: false,
                    select_all_or_cancel: "全选",
                    delete_body_array_state: []
                }));
                await this.list_and_set()
                this.lazy_load()
            },
        });
        add_delete_button_function_to_delete_box("modal_comfirm");
    }
    list_and_set = async () => {
        await this.props.standard_face_database_store.get_face_store_information(this.props.standard_face_database_store.nowChoseWhichFaceStore, this.state.per_page, this.props.AdminStore.token)
    }
    select_my_check_box_function = (item, e) => {//复选框函数
        console.log(e.target.checked)
        if (e.target.checked) {
            this.state.delete_body_array_state.push(item);
            this.setState(prevState => ({
                delete_body_array_state: this.state.delete_body_array_state,
            }));
        } else {
            let index_arr = []
            for (let [index, item1] of this.state.delete_body_array_state.entries()) {
                if (item1.user === item.user) {
                    index_arr.push(index)
                }
            }
            for (let [index, item] of index_arr.entries()) {
                this.state.delete_body_array_state.splice(item, 1)
            }
            console.log(this.state.delete_body_array_state)
            this.setState((prevState) => ({
                delete_body_array_state: this.state.delete_body_array_state
            }))

        }
    };
    get_detail_information = async () => {
        await this.props.standard_face_database_store.get_face_store_information(this.props.standard_face_database_store.nowChoseWhichFaceStore, this.state.per_page, this.props.AdminStore.token)
    }
    lazy_load = () => {
        picture_lazy_load('human_body_management_ul', 'ren_ti_jian_suo_right_ul_li_img', 218)
    }
    handleOk = async (img_base64, people_name, nowChoseWhichFaceStore, token) => {
        let ok_result = false
        if (people_name === '') {
            message.error("人脸名称不能为空");
        } else if (people_name.length > 7) {
            message.error("不允许超过7个字符");
        } else if (img_base64 === '') {
            message.info("您还未选择图片");
        } else {
            this.setState({
                confirmLoading: true,
            });
            const res = await this.props.standard_face_database_store.upload_img(img_base64, people_name, nowChoseWhichFaceStore, token)
            if (res) {
                ok_result = true
            }
        }
        return ok_result
    }
    handleCancel = () => {
        this.setState((prevState) => ({
            new_face_visible: false
        }))
    }
    beforeUpload = async (file) => {
        const img_base64 = await new Promise((resolve, reject) => {
            var fr = new FileReader();
            fr.onload = () => {
                const result = img_format_size(file)//校验格式
                if (result) {
                    resolve(fr.result)
                }
            };
            fr.readAsDataURL(file);
        });
        this.setState((prevState) => ({
            img_base64: img_base64
        }))
    }

}
